package com.video.video.controller;

import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@Controller
//@ServerEndpoint("/ServerWebSocket")
public class ServerWebSocketController {
    private Session session;

    private static CopyOnWriteArraySet<ServerWebSocketController> serverWebSockets=new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        serverWebSockets.add(this);
        System.out.println("有新的连接，总数"+serverWebSockets.size());
    }

    @OnClose
    public void onClose(){
        serverWebSockets.remove(this);
        System.out.println("有新的断开，总数"+serverWebSockets.size());
    }

    @OnMessage
    public void onMessage(String message){

        System.out.println(message);

        send(message);
    }


    public void send(String message){
        for (ServerWebSocketController webSocket:serverWebSockets){
            try {
                webSocket.session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
